import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import getuser from '../../../../atoms/getuser';
import { tbfdmenu, tbfdrolemenu } from '../../../../atoms/db';
import delfile from '../../file/del';

const logger = anylogger('pages/api/admin/menu/del.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	menuid: string;
}

/**
 * 删除角色
 */
const handler = an48<Result>();

handler.delete(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const user = await getuser(req);
		if (!user || user.role !== 'admin') {
			res.status(200).json({
				ok: false,
				message: 'Not allowd to do so'
			});
			return;
		}
		const { menuid } = req.body as Message;

		if (!menuid) {
			res.status(200).json({
				ok: false,
				message: 'ID required'
			});
			return;
		}

		// if children exists, do not allowed to delete
		const child = await tbfdmenu().first('*').where({
			pid: menuid
		});
		if (child) {
			res.status(200).json({
				ok: false,
				message: '请先删除子菜单'
			});
			return;
		}

		const menu = await tbfdmenu().first('*').where({ menuid });
		if (!menu) {
			res.status(200).json({
				ok: false,
				message: '不存在'
			});
			return;
		}

		await tbfdmenu().del().where({ menuid });
		await tbfdrolemenu().del().where({ menuid });
		// 删除菜单文件
		await delfile(menu.icon);
		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
